﻿//////////////////////////////////////////////////////////////////////////////
//
// Copyright © 1998-2024 Glodon Company Limited.
//
// Licensed under the MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the “Software”),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////////
#include "CmdFinishDrawStructurePlateHoleProfile.h"
#include "GbmpModelViewUtil.h"
#include "GmUiStructureCommandRegister.h"
#include "StructureCmdIds.h"

#include "IModelView.h"
#include "ISelection.h"
#include "IUserTransaction.h"
#include "UserTransactionGroupUtils.h"
#include "UniIdentity.h"
#include "IUiDocument.h"
#include "UiCommonDialog.h"
#include "IEditMode.h"
#include "StructureEditModeTypes.h"
#include "IStructurePlateHoleEditModeBehavior.h"
#include "StructureEditProfileUtils.h"
#include "StructureInstanceCmdUtils.h"
#include "GbmpBuiltInCategoryUniIdentitiesNew.h"
#include "ProfileUsedModelLineUtils.h"
#include "StructurePlateHoleInput.h"
#include "IStructurePlateHole.h"
#include "CmdStatusUtils.h"
#include "IHighlights.h"
#include "UiDocumentViewUtils.h"

#include "EnableCompileWarning_The_LAST_IncludeInCpp.h"

using namespace gcmp;

REGISTER_GM_COMMAND(CmdFinishDrawStructurePlateHoleProfile);

CmdFinishDrawStructurePlateHoleProfile::CmdFinishDrawStructurePlateHoleProfile()
    : GbmpCommandBase(ID_CMD_EDIT_STRUCTURE_PLATE_HOLE_FINISH)
{
}

CmdFinishDrawStructurePlateHoleProfile::~CmdFinishDrawStructurePlateHoleProfile()
{
}

OwnerPtr<IAction> CmdFinishDrawStructurePlateHoleProfile::ExecuteCommand(const CommandParameters& cmdParams)
{
    IUiDocument* pUIDoc = UiDocumentViewUtils::GetCurrentUiDocument();
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pUIDoc != nullptr, L"没有当前文档",L"GDMPLab",L"2024-03-30");

    IDocument* pDoc = UiDocumentViewUtils::GetCurrentDocument();
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pDoc, L"无效的pDoc指针",L"GDMPLab",L"2024-03-30");

    IModelView* pModelView = UiDocumentViewUtils::GetCurrentModelView();
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pModelView != nullptr, L"没有当前视图",L"GDMPLab",L"2024-03-30");

    const IEditMode* pProfileEditMode = IEditMode::Get(pDoc, StructureEditModeTypes::StructurePlateHoleModeType);
    DBG_WARN_AND_RETURN_UNLESS(pProfileEditMode, nullptr, L"获取板洞编辑模式失败！",L"GDMPLab",L"2024-03-30");

    const IStructurePlateHoleEditModeBehavior* pProfileEDBehavior = quick_cast<IStructurePlateHoleEditModeBehavior>(pProfileEditMode->GetEditModeBehavior());
    DBG_WARN_AND_RETURN_UNLESS(pProfileEDBehavior, nullptr, L"pProfileEDBehavior为空！",L"GDMPLab",L"2024-03-30");
    
    bool bIsCreating = pProfileEditMode->GetIsCreating();
    ElementId familyId = pProfileEDBehavior->GetEditingFamilyId();
    ElementId instanceTypeId = pProfileEDBehavior->GetEditingInstanceTypeId();
    ElementId floorId = pProfileEDBehavior->GetHostId();

    std::vector<IModelLine*> profileCurves;
    ProfileUsedModelLineUtils::GetStructureProfileModelLinesInCurrDoc(pDoc, profileCurves);

    if (profileCurves.empty())
    {
        UiCommonDialog::ShowMessageBox(GBMP_TR(L"警告"), GBMP_TR(L"轮廓为空，无法完成绘制轮廓！"), (int)UiCommonDialog::ButtonType::OK);
        return nullptr;
    }

    // 检查轮廓线是否合法，并做提示
    if (!StructureEditProfileUtils::CheckForValidLoops(profileCurves, GbmpModelViewUtil::GetWorkPlaneCoordinate(pModelView), false, false))
        return nullptr;

    if (bIsCreating)
    {
        OwnerPtr<StructurePlateHoleElementInput> opInput = NEW_AS_OWNER_PTR(StructurePlateHoleElementInput);
        OwnerPtr<IUserTransaction> ut = IUserTransaction::Create(pDoc, GBMP_TR(L"完成编辑轮廓实例"));
        {
            IEditMode* pEditMode = IEditMode::Get(pDoc, StructureEditModeTypes::StructurePlateHoleModeType);
            DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pEditMode, L"获取当前编辑模式失败！",L"GDMPLab",L"2024-03-30");
            // 退出编辑模式，确保Instance Calculators可以开始工作
            pEditMode->EndEditing(pDoc);

            bool bOk = StructureInstanceCmdUtils::GenerateStructurePlateHoleInput(pDoc, pModelView, GetCategory(), GetCategorySecondKey(),
                familyId, instanceTypeId, *opInput);
            DBG_WARN_AND_RETURN_NULLPTR_UNLESS(bOk, L"板洞的input数据生成失败",L"GDMPLab",L"2024-03-30");

            opInput->HostId = floorId;
            opInput->ProfileCurves = profileCurves;

            IStructurePlateHole* pPlateHole = IStructurePlateHole::Create(opInput.get());

            ISelection::Get()->Clear(pDoc);
            IHighlights::Get()->Clear();
        }
        ut->Commit();
    }
    else
    {
        ElementId instanceId = pProfileEditMode->GetEditingElementId();
        OwnerPtr<StructurePlateHoleEditElementInput> opInput = NEW_AS_OWNER_PTR(StructurePlateHoleEditElementInput);
        opInput->Document = pDoc;
        opInput->InstanceId = instanceId;
        opInput->ProfileCurves = profileCurves;

        OwnerPtr<IUserTransaction> ut = IUserTransaction::Create(pDoc, GBMP_TR(L"完成编辑轮廓实例"));
        {
            IEditMode* pEditMode = IEditMode::Get(pDoc, StructureEditModeTypes::StructurePlateHoleModeType);
            DBG_WARN_AND_RETURN_UNLESS(pEditMode, nullptr, L"获取当前编辑模式失败！",L"GDMPLab",L"2024-03-30");
            // 退出编辑模式，确保Instance Calculators可以开始工作
            pEditMode->EndEditing(pDoc);

            IStructurePlateHole* pPlateHole = IStructurePlateHole::Edit(opInput.get());

            if (!pPlateHole)
            {
                UserTransactionGroupUtils::AbortLatestActive(pDoc);
                return nullptr;
            }
            ISelection::Get()->Clear(pDoc);
            IHighlights::Get()->Clear();
        }
        ut->Commit();
    }
    UserTransactionGroupUtils::CommitLatestActive(pDoc);

    pUIDoc->UpdateView();

    return nullptr;
}

bool CmdFinishDrawStructurePlateHoleProfile::IsEnabled() const
{
    if (!CommandBase::IsEnabled())
    {
        return false;
    }

    CMD_ONLY_ENABLE_IN_PROJECT_ENVIRONMENT
}
bool CmdFinishDrawStructurePlateHoleProfile::IsVisible() const
{
    CMD_ONLY_VISIBLE_IN_PROJECT_ENVIRONMENT
}

Int32 CmdFinishDrawStructurePlateHoleProfile::GetCategorySecondKey() const
{
    return 0;
}

UniIdentity CmdFinishDrawStructurePlateHoleProfile::GetCategory() const
{
    return BuiltInCategoryUniIdentities::BICU_STRUCTURE_PLATE_HOLE;
}
